// pages/recommendShopGoodList/recommendShopGoodList.js
import api from '../../utils/api.js'
import {
    divideByHundred
} from '../../utils/util.js'
const app = getApp();
import { config } from '../../utils/config'
const unitZn = { //中文单位
    0: "kg",
    1: "份",
    2: "箱",
    3: "包",
    4: "袋",
    5: "斤"
}

Page({
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        shopList: [], //筛选出来的店铺
        disableShopList: [],
        selectGoods: [], // 选择的单品
        distance: [], //距离
        label: [], //店铺可售卖菜谱标签
        tip: false,
        talk: [], // 店铺 评***价
        foodsNum: [0, 0, 0, 0, 0, 0, 0, 0, 0, ], //选择食材的数量
        erveyShopTotalMoney: [0, 0, 0, 0, 0, 0, 0, 0, 0, ],
        imgUrl: config.imgUrl,
        list: [
            { url: "https://images.weigeee.com/20190902/d807f19c6423d192b8901b8bf44b0fd8.jpg", name: "蔡夫人" },
            { url: "https://images.weigeee.com/20190902/9bb905d4038f05eab2057df991db4d38.png", name: "谊品生鲜" },
            { url: "https://images.weigeee.com/20190902/afca7e69786139aaca317dcc8b7b3010.png", name: "厨鲜生" },
        ]
    },
    // 去推荐码页面
    goToRecommendCode() {
        wx.redirectTo({
            url: '/pages/member-friend/member-friend'
        })
    },
    //单品加减
    add(e) {
        console.log('eeeee', e)
        let fIndex = e.currentTarget.dataset.findex //父级店铺索引
        let labelIndex = e.currentTarget.dataset.labelindex; //label内的 索引
        let shopId = e.currentTarget.dataset.shopid;
        let curProduct = this.data.shopList[fIndex].label[labelIndex] // 当前 单品
        curProduct.number += 1
        if (curProduct.number > 0) {
            curProduct.mark = true
        }
        //动态值，不要使用es6的末班字符串
        let good = 'shopList' + '[' + fIndex + ']' + '.label' + '[' + labelIndex + ']'
        this.setData({
            [good]: curProduct
        });

        //计算当前——店铺总价，并且只能在一家店铺下单
        this.curTotalMoney(fIndex)

        // wx.setStorageSync('cacheShopId', shopId)
        // // 判断用户是否切换店铺操作
        // if (wx.getStorageSync('cacheShopId')) { //缓存的店铺id存在时
        //   let cacheShopId = wx.getStorageSync('cacheShopId')
        //   if (cacheShopId == shopId) {

        //   } else { //切换店铺时，重新赋值缓存值
        //     wx.showModal({
        //       content: '您确定要切换店铺下单吗？',
        //       success(res) {
        //         if (res.confirm) {
        //           cacheIndex = shopId
        //           //切换店铺时清除其他店铺的状态
        //           that.clearConfirmState(fIndex)

        //         } else if (res.cancel) {
        //           //点击取消时，无法确认上家店铺的索引值
        //           cacheIndex = cacheIndex
        //           console.log('用户点击取消', cacheIndex)
        //           that.clearCancelState(cacheIndex)
        //         }
        //       }
        //     })

        //   }

        // } else { //第一次选择店铺单品时，缓存当前店铺id
        //   cacheIndex = shopId
        // }

    },
    reduce(e) {
        let fIndex = e.currentTarget.dataset.findex //父级店铺索引
        let labelIndex = e.currentTarget.dataset.labelindex; //label内的 索引
        let shopId = e.currentTarget.dataset.shopid;
        let curProduct = this.data.shopList[fIndex].label[labelIndex] // 当前 单品
        if (curProduct.number >= 1) {
            curProduct.number -= 1
            if (curProduct.number === 0) {
                curProduct.mark = false
            }
        }
        //动态值，不要使用es6的末班字符串
        let good = 'shopList' + '[' + fIndex + ']' + '.label' + '[' + labelIndex + ']'
        this.setData({
            [good]: curProduct
        });

        //计算当前——店铺总价，并且只能在一家店铺下单
        this.curTotalMoney(fIndex)
    },
    onLoad: function(options) {
        //每次进入页面重新加载经纬度
        const Jingwei = wx.getStorageSync('address')

        if (options.type == 0) { //从单品菜篮——进入店铺列表
            let selectGoods = wx.getStorageSync('select-goods')
            let shopId = []; // 店铺id，不需操作，只是为了请求附近店铺做的声明变量，参数传递
            let goodsId = []; //单品id
            selectGoods.forEach((ele, i) => {
                goodsId.push(ele.id)
            })
            this.choiceGoodsShop(Jingwei.latitude, Jingwei.longitude, shopId, goodsId);
            this.setData({
                selectGoods,
                type: options.type
            })

        } else if (options.type == 2) { //单品菜——从支付成功再次进入-筛选店铺
            let alreadyShopId = JSON.parse(options.alreadyShopId)
            let selectGoods = wx.getStorageSync('select-goods') //本地存储的 单品菜

            let shopId = []; // 店铺id
            let productId = []; //单品id

            selectGoods = selectGoods.filter((ele, i) => {
                return ele.flag == true
            })
            selectGoods.forEach((ele, i) => {
                    //菜篮所有的单品id都加入
                    productId.push(ele.id)
                    alreadyShopId.forEach((sEle, sIndex) => {
                        if (sEle == ele.id) { //灰色掉-已购买的单品
                            return ele.greyOff = true
                        }
                    })
                })
                //覆盖本地存储
            wx.setStorageSync('select-goods', selectGoods)
                //删除已购买的单品，再重新请求
            productId = productId.filter(item => alreadyShopId.indexOf(item) == -1)
            this.choiceGoodsShop(Jingwei.latitude, Jingwei.longitude, shopId, productId);
            this.setData({
                selectGoods,
                type: 2
            })
        }
    },
    // 点击单品选择时，计算当前店铺选择的食材的总价与 选择 的食材的数量
    curTotalMoney(fIndex) {
        let totalMoney = 0;
        let totalGoodsNum = 0;
        let shopList = this.data.shopList;
        let curShop = shopList[fIndex];
        let curShopLabel = curShop.label;

        curShopLabel.forEach((ele, index) => {
            //计算每个有数量的单品
            if (ele.mark) {
                totalMoney += ele.number * ele.price
                totalGoodsNum += ele.number
            }
        })
        curShop.totalGoodsNum = totalGoodsNum;
        curShop.totalMoney = totalMoney;

        //动态值
        let singleShop = 'shopList' + '[' + fIndex + ']'
        this.setData({
            [singleShop]: curShop
        });
    },


    //下单—————去下单
    goOrder(e) {
        let that = this;

        let fIndex = e.currentTarget.dataset.findex; //父级店铺索引
        let curShop = this.data.shopList[fIndex]; // 当前下单 店铺的信息
        let shopId = e.currentTarget.dataset.shopid //店铺id
        let shopAddress = this.data.shopList[fIndex].address;
        let totalMoney = curShop.totalMoney;
        let vegetale = curShop.label; //拿到当前店铺 可售卖的菜
        wx.setStorageSync('singleShopList', curShop)

        if (curShop.totalGoodsNum == 0) {
            wx.showToast({
                title: '当前店铺您还未选择商品',
                icon: 'none',
                mask: true
            })
            return false
        } else {
            wx.setStorageSync('vegetaleCurrent', vegetale)

            wx.navigateTo({
                url: `/pages/order/order?shopId=${shopId}&fIndex=${fIndex}&shopAddress=${shopAddress}&totalMoney=${totalMoney}&singleType=1`,
            })

        }
    },
    //附近店铺
    choiceGoodsShop(lat, lng, shopId, goodsId) {
        let that = this
        return new Promise((resolve, reject) => {
            http.request({
                url: api.choiceMerchantShop,
                method: "POST",
                data: {
                    lat: lat,
                    lng: lng
                },
                success: (res) => {
                    if (res.code == 200) {
                        const data = res.data;
                        data.forEach((ele) => {
                                shopId.push(ele.id)
                                ele.totalGoodsNum = 0;
                                ele.totalMoney = 0;
                            })
                            //附近店铺
                        if (data) {
                            console.log('222222222', data)
                                // 如果条件是 满多少送商品，则拿到商品id请求商品名称
                                // 循环请求，顺序拿到，判断添加
                            that.toDistanceFixed(data)
                            data.forEach((ele, index) => {
                                ele.yh.forEach((sEle, sIndex) => {
                                    if (sEle.pon.type == 2) {
                                        let id = Number.parseInt(sEle.discounts)
                                        let dataPromise = that.showDetail(id)
                                        dataPromise.then((product_data) => {
                                            sEle.product_name = product_data.name
                                        })
                                    }
                                })
                            })

                            let promises = data.map((ele, index) => {
                                //可售卖菜谱
                                return that.shopGoodsLabel(ele.id, goodsId)
                            })
                            Promise.all(promises).then((allData) => {
                                console.log("可售卖菜谱allData", allData)
                                    //当有店铺，但店铺没有 可售卖的菜谱
                                data.forEach((ele, index) => {
                                    allData.forEach((sEle, sIndex) => {
                                        // 索引判断不是很严谨
                                        if (index == sIndex) {
                                            ele.label = sEle
                                        }
                                    })
                                })

                                that.setData({
                                    shopList: data
                                })

                            }).catch((err) => {
                                console.log(err);
                            })

                            // //评***价
                            let promises2 = data.map((ele, index) => {
                                return that.shopTalk(ele.id)
                            })
                            Promise.all(promises2).then((allData) => {
                                    console.log('评***价', allData)
                                    data.forEach((ele, index) => {
                                        allData.forEach((sEle, sIndex) => {
                                            if (index == sIndex) {
                                                let comment = that.getShopTalk(sEle)
                                                ele.comment = comment
                                            }
                                        })
                                    })
                                    that.setData({
                                        shopList: data
                                    })
                                }).catch((err) => {
                                    console.log(err);
                                })
                                // try {
                                //   //拿到 所有店铺的 评论
                                //   that.getShopTalk(shopId)
                                //   that.getGoodsLabel(shopId, goodsId)

                            // } catch (err) {
                            //   console.log('err', err)
                            // }

                        }
                        //取得经纬度，未筛选的店铺-过渡数组，下方要处理
                        resolve(data);

                    } else if (res.data.code == 201) {
                        that.setData({
                            tip: true
                        })
                        console.log('201-您的附近暂时还没有商家')
                    }
                },
                fail: (res) => {
                    console.log('error', res)

                }
            })
        })

    },
    //获取店铺可售卖的单品, 如果当前店铺没有可售卖的单品，则删除
    //以shopId循环请求，顺序拿到返回值shopGoodsLabel
    shopGoodsLabel(shopId, goodsId) {
        let that = this
        let ret = []
        let num = goodsId.join(",");
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.sureShopProducts,
                method: "POST",
                data: {
                    id: shopId, //商户id
                    ids: num, //多个单品id
                    page: 1,
                    size: 8
                },
                success: (res) => {
                    let data = res.data;
                    // console.log('单品',data)
                    if (data instanceof Array && data.length > 0) {
                        data.forEach((ele) => {
                            ele.number = 0
                            ele.mark = false;
                        })
                    }
                    resolve(data);
                    if (res.data.error_code == 201) {
                        //该商户没有任何用户想要购买的商品,所以不予推荐
                    } else if (res.code == 200) {}
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })
    },
    getGoodsLabel(shopId, goodsId) {
        let selectGoods = this.data.selectGoods; // 本地购物存储的 单品数量 要加在label标签上
        //shopId为一个数组
        let promises = shopId.map((item, index) => {
            return this.shopGoodsLabel(item, goodsId, index);
        });
        Promise.all(promises).then((allData) => {
            // allData = allData.filter((ele,index) => {
            //   if (ele != undefined) { //去除错误201的店铺,否则会报错,渲染数据失败
            //     return true
            //   }
            // })

            // 循环全部-单品加选择状态
            allData.forEach((ele) => {
                if (ele != undefined) {
                    ele.forEach((sEle, sIndex) => {
                        //添加产品选择状态
                        sEle.productState = false;
                        //中文单位转换
                        sEle.unitZn = unitZn[sEle.unit]
                            //本地存储的单品的数量，与接口获取可售卖的单品，比较添加数量
                        selectGoods.forEach((good, gIndex) => {
                            if (sEle.id == good.id) {
                                sEle.num = good.num
                            }
                        })
                    })
                }
            })
            this.setData({
                label: allData
            })
        }).catch((err) => {
            console.log(err);
        })
    },
    toDistanceFixed(arr) {
        const ret = arr.map((item) => {
            if (item.distance == 0) {
                return 0
            }
            return item.distance.toFixed(2)
        })
        this.setData({
            distance: ret
        })
    },

    // 拿到满送的商品 名称
    showDetail(id) {
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.getOnE,
                method: "POST",
                data: {
                    id: id,
                },
                success: (res) => {
                    let data = res.data
                    resolve(data)
                },
                fail: (res) => {
                    console.log('error', res)
                }
            })
        })


    },
    // 获取 每个店铺的评***价
    shopTalk(id) {
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.getAppraises,
                method: "POST",
                data: {
                    page: 1,
                    size: 10,
                    id: id //店铺id
                },
                success: (res) => {
                    if (res.dcode == 200) {
                        let data = res.data;
                        resolve(data);
                    } else if (res.data.error_code == 201) { //店铺 暂无评***价时
                        let msg = [];
                        resolve(msg)
                    }
                },
                fail: (res) => {
                    console.log('error', res)

                }
            })

        })

    },
    getShopTalk(data) {

        // 一一对应店铺评***价 - 随机取三条 - 评分大于>= 4且有内容，然后拼接，循环滚动
        let num = 3; //随机取3条
        let comment = []; // 重构的 店铺评***价
        let randomMent = [] //随机产生3条好评
        if (data.length = 0) {

        } else {
            for (let i in data) {
                //重构结构，去除评***价数量，好评率字段
                if (data[i] instanceof Object) {
                    comment.push(data[i])
                        // if (data[i].grade >= 4 && data[i].grade < 6) {}
                }
            }
        }
        // console.log('comment', comment)
        // 获取随机数
        // var rand = Math.floor(Math.random() * comment.length);
        // // 随机从数组中取出某值（不会改变原数组）
        // randomMent = comment.slice(rand, 1)[0];
        // console.log('randomMent', randomMent)
        return comment
    },

    // 去店铺 评***价页面
    enterShopEvaluationList(e) {
        let shopId = e.currentTarget.dataset.shopid
        wx.setStorageSync('evalutionListShopId', shopId)
        wx.navigateTo({
            url: `/pages/userEvaluationList/userEvaluationList?shopId=${shopId}`,
        })
    },
    onUnload: function() {
        let selectGoods = wx.getStorageSync('select-goods')
        if (selectGoods) {
            selectGoods.forEach((ele, i) => {
                return ele.greyOff = false
            })
            wx.setStorageSync('select-goods', selectGoods)
        }

    },
})